<template>
    <list-layout>
        <div slot="search">
            <el-form :model="queryParams" :inline="true" label-position="right" ref="queryForm" v-show="showSearch" label-width="130px">

                <!-- 规则编码 -->
                <el-form-item :label="$t('transferRules.ruleCode')" prop="ruleCode">
                    <el-input v-model="queryParams.ruleCode" :placeholder="
                      $t('public.placeholder', {
                        placeholder: $t('transferRules.ruleCode'),
                      })
                    " clearable size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <!-- 物料名称 -->
                <el-form-item :label="$t('basicData.materialName')" prop="divisionName">
                    <el-input v-model="queryParams.materialName" :placeholder="
                      $t('public.placeholder', {
                        placeholder: $t('basicData.materialName'),
                      })
                    " clearable size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <!-- 物料类型 -->
                <el-form-item :label="$t('basicData.materialType')" prop="materialType">
                    <el-input v-model="queryParams.materialType" :placeholder="
                      $t('public.placeholder', {
                        placeholder: $t('basicData.materialType'),
                      })
                    " clearable size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item :label="$t('basicData.materialNo')" prop="materialCode">
                    <el-input v-model="queryParams.materialCode" :placeholder="
                      $t('public.placeholder', {
                        placeholder: $t('basicData.materialNo'),
                      })
                    " clearable size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>
            </el-form>
            <div style="display: flex; justify-content: center">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("public.search") }}</el-button>
                <el-button icon="el-icon-refresh" class="resectBtn" size="mini" @click="resetQuery">{{
          $t("public.reset")
        }}</el-button>
            </div>
        </div>
        <div class="app-container">
            <div class="container-header">
                <div class="header-left"> {{ $t("transferRules.rulesMaterial") }} </div>
            </div>
            <div class="container-table">
                <el-table class="table-fixed" :row-class-name="tableRowClassName" ref="multipleTable" :key="tableKey" v-loading="loading" :height="tableHeight" border :data="tableData" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" fixed="left" align="center" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('transferRules.ruleCode')" sortable v-if="columns[0].visible" align="left" prop="ruleCode" min-width="180" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('basicData.materialNo')" sortable v-if="columns[1].visible" align="left" prop="materialCode" min-width="180" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('basicData.materialName')" sortable v-if="columns[2].visible" align="left" prop="materialName" min-width="180" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('basicData.materialType')" sortable v-if="columns[3].visible" align="left" prop="materialType" min-width="180" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('factory.factoryName')" sortable v-if="columns[7].visible" align="left" prop="factoryName" min-width="180" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('transferRules.currentTactics')" sortable v-if="columns[4].visible" align="left" prop="currentTactics" min-width="180" :show-overflow-tooltip="true" >
                        <template slot-scope="scope">{{ formatTactics(scope.row.currentTactics) }}</template>
                    </el-table-column>
                    <el-table-column :label="$t('transferRules.tactics_holder',{text_holder:$t('public.startTime')})" sortable v-if="columns[5].visible" align="left" prop="tacticsStartTime" min-width="180" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('transferRules.tactics_holder',{text_holder:$t('public.executionTime')})" sortable v-if="columns[6].visible" align="left" prop="tacticsExecutionTime" min-width="180" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('public.opera')" fixed="right" align="center" width="80">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                <table-body-btn type="gwedit" :name="$t('transferRules.editTactics')" @click.native="handleEdit(scope.row)" v-hasPermi="['ny-iqc:materielBind:editTactics']"/>
                                <!-- <table-body-btn type="feedback" name="编辑物料" @click.native="handleMaterial(scope)" /> -->
                                <!-- <table-body-btn type="delete" name="删除规则" @click.native="handleDel(scope)" /> -->
                            </div>
                        </template>
                    </el-table-column>

                </el-table>

                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" layout="total, sizes, prev, pager, next, jumper" />
            </div>

            <!-- 打印 -->
            <el-dialog :title="$t('inspectionManagement.printer')" :visible.sync="printerOpen" center top="34vh" width="500px" append-to-body :fullscreen="fullscreen">
                <el-form :model="queryParams" ref="printerForm" v-model="printerForm" label-position="top">
                    <el-form-item :label="$t('inspectionManagement.printerNum')" prop="auditor">
                        <el-input v-model="queryParams.printerNum" min="1" type="number" :placeholder="
                $t('public.placeholder', {
                  placeholder: $t('inspectionManagement.printerNum'),
                })
              " clearable size="small" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitPrinter" icon="el-icon-check" size="small">{{ $t("public.define") }}</el-button>
                </div>
            </el-dialog>

            <el-drawer :with-header="false" :visible.sync="drawer" size="50%" :direction="direction" :before-close="handleClose">
                <div class="app-container">
                    <div class="container-header">
                        <div class="header-left">
                            {{ $t("inventoryManagement.editInspection") }}
                        </div>
                    </div>
                    <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">{{ $t("inventoryManagement.addInspection") }}</el-button>
                        </el-col>
                        <el-col :span="1.5">
                            <el-button type="primary" icon="el-icon-edit-outline" size="mini" @click="handleApproval">{{ $t("inventoryManagement.approval") }}</el-button>
                        </el-col>
                        <el-col :span="1.5">
                            <el-button type="primary" icon="el-icon-upload2" size="mini">{{ $t("inventoryManagement.topping") }}</el-button>
                        </el-col>
                        <el-col :span="1.5">
                            <el-button type="primary" icon="el-icon-upload" size="mini">{{ $t("inventoryManagement.export") }}</el-button>
                        </el-col>
                    </el-row>
                    <div class="container-table">
                        <el-table stripe v-loading="loading" :data="incomingList" @selection-change="handleSelectionChange">
                            <el-table-column type="selection" width="55" align="center" />
                            <el-table-column :label="$t('inventoryManagement.inspectionBatchNo')" align="left" prop="noticeId" min-width="140" />
                            <el-table-column :label="$t('inventoryManagement.unit')" align="left" prop="noticeTitle" :show-overflow-tooltip="true" />
                            <el-table-column :label="$t('inventoryManagement.recheckSheet')" align="left" :show-overflow-tooltip="true">
                                <template slot-scope="scope">
                                    <span>{{
                    scope.row.noticeType == "1"
                      ? $t("message.notice")
                      : $t("message.announcement")
                  }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column :label="$t('inventoryManagement.approvalTime')" align="left" prop="hasRead">
                                <template slot-scope="scope">
                                    {{
                    scope.row.hasRead == 0
                      ? $t("message.unread")
                      : $t("message.read")
                  }}
                                </template>
                            </el-table-column>
                            <el-table-column :label="$t('inventoryManagement.rejectReason')" align="left" prop="rejectReason" :show-overflow-tooltip="true" />
                            <el-table-column :label="$t('inventoryManagement.approvalStatus')" align="left" prop="approvalStatus" :show-overflow-tooltip="true" />
                            <el-table-column :label="$t('inventoryManagement.inspectionOrderstatus')" align="left" prop="inspectionOrderstatus" min-width="120" :show-overflow-tooltip="true" />
                        </el-table>
                    </div>
                </div>
                <div class="drawer-footer">
                    <el-button icon="el-icon-close" size="mini" @click="drawerClose" class="drawer-close">{{ $t("public.close") }}</el-button>
                </div>
            </el-drawer>
            <!-- 审批 -->
            <el-dialog title="紧急放行审批" :visible.sync="releaseOpen" center top="14vh" width="500px" append-to-body :fullscreen="fullscreen">
                <el-form :model="releaseForm" ref="releaseForm" label-position="top">
                    <el-form-item :label="$t('inventoryManagement.isPassApproval')" prop="release">
                        <el-radio-group v-model="releaseForm.release">
                            <el-radio label="1">{{$t("inventoryManagement.pass")}}</el-radio>
                            <el-radio label="0">{{$t("inventoryManagement.reject")}}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitRelease" icon="el-icon-check" size="small">{{ $t("public.define") }}</el-button>
                </div>
            </el-dialog>


            <!-- 编辑策略 -->
            <el-dialog :title="$t('transferRules.editTactics')" :visible.sync="ruleOpen" center top="14vh" width="700px" append-to-body :fullscreen="fullscreen">
                <el-form :model="ruleModal" size="small" label-suffix=":" ref="ruleFormRef" :rules="rules" label-width="88px">
                    <el-row :gutter="15">
                        <el-col :span="10">
                            <el-form-item :label="$t('transferRules.ruleCode')" prop="ruleCode">
                                <el-input v-model="ruleModal.ruleCode" clearable disabled
                                    :placeholder="
                                    $t('public.placeholder', {
                                        placeholder: $t('transferRules.ruleCode'),
                                    })
                                    "
                                    size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="15">
                        <el-col :span="10">
                            <el-form-item :label="$t('statistics.materialName')" prop="materialName">
                                <el-input v-model="ruleModal.materialName" clearable disabled
                                    :placeholder="
                                    $t('public.placeholder', {
                                        placeholder: $t('statistics.materialName'),
                                    })
                                    "
                                    size="small" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="15">
                        <el-col :span="12">
                            <el-form-item :label="$t('transferRules.chuangeTactics')" prop="currentTactics">
                                <el-select  style="width:100%"
                                    v-model="ruleModal.currentTactics"
                                    :placeholder="
                                    $t('public.select_holder', {
                                        placeholder: $t('transferRules.tactics'),
                                    })
                                    "
                                    :loading="tacticsLoading">
                                    <el-option
                                        v-for="item in tacticsOptions" :key="item.value" :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="15">
                        <el-col :span="24">
                            <el-form-item :label="$t('public.upload')">
                                <file-upload v-model="ruleModal.uploadAttachments" :ifDelete="false" :otherList="otherList" ref="incomingFiles" :bizId="rowId" @change="(fileList)=>incomingFileChange(fileList)"></file-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>

                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="ruleOpen = false" :loading="loading" size="small">{{$t('public.close')}}</el-button>
                    <el-button type="primary" @click="submitRule" :loading="loading" size="small">{{$t('public.save')}}</el-button>
                </div>
            </el-dialog>
        </div>
    </list-layout>
</template>

<script>
import {getType, refreshCache} from '@/api/basic/dict/type'
import {
  addNcr,
  editAcceptReturns,
  getAcceptReturns,
  getAudit,
  getAuditCheck,
  getAuditEcho,
  getCollectionCheck,
  getInspectionCheck,
  getMinFlawAll,
  getNCRDetail,
  getNcrReviewCheck,
  getPrintCheck,
  getReleaseApproval,
  getReleaseCheck,
  getReport,
  getReturn,
  getReview,
  incomingList,
} from '@/api/inspectionManagement/inspectionManagement'
import {mapGetters, mapState} from 'vuex'
import {listALLFactory} from '@/api/basic/factory'
import FileUpload from '@/components/FileUpload'
import {listMaterialType} from '@/api/basic/materialtype'
import SelectUserDialog from '@/views/components/SelectUserDialog'
import {getToken} from '@/utils/auth'

import { transferRulesList, delTransferRules,addTransferRules,editTransferRules, editMaterialBind, editMaterialTactics } from '@/api/inspectionManagement/transferRules'
import DivisionDialog from '@/views/components/DivisionDialog'
import { getMaterialBindList, addMaterialBind, delMaterialBind, getTransferRulesInfo, carryOutList } from '@/api/inspectionManagement/transferRules'
import {geFileByBiz} from '@/api/file/file'

export default {
    name: 'RulesMaterial',
    dicts: [
        'NYIQC_ENABLE_STATUS',
        'NYIQC_SHEET_STATUS', //检验单状态
        'NYIQC_NCR_DECISION', //使用决策
        'NYIQC_BATCH',
        'NYIQC_NCR_QCLASS',
        'NYIQC_EXEMPTEDOASTATUS', //免检审批状态
        'NYIQC_EXEMPTED', //免检
        'NYIQC_AUDIT_RESULT',
        'NYIQC_RULE_TACTICS', // 策略
    ],
    components: {
        FileUpload,
        SelectUserDialog,
        DivisionDialog,
    },
    data() {
        return {
            direction: 'rtl',
            factoryList: [],
            optionLoading: false,
            returnInspection: false,
            returnKey: 0,
            releaseForm: {
                release: '1',
            },
            releaseOpen: false,
            // 表格列
            columns: [
                { key: 0, visible: true, label: '规则编码' },
                { key: 1, visible: true, label: '物料编码' },
                { key: 2, visible: true, label: '物料名称' },
                { key: 3, visible: true, label: '物料类型' },
                { key: 4, visible: true, label: '当前策略' },
                { key: 5, visible: true, label: '策略开始时间' },
                { key: 6, visible: true, label: '策略结束时间' },
                { key: 7, visible: true, label: '厂区名称' }
            ],
            printerVisible: false,
            printerUsingDecision: null,
            addInspection: false,
            minFlawOptions: [],
            showSearch: true,
            tableHeight: 'calc(100vh - 308px)',
            printerId: null,
            previewModel: {},
            ncrRefresh: 0,
            ncrModel: {
                ncrType: 0,
            },
            factoryList: [],
            drawer: false,
            approvalOpen: false,
            printerOpen: false,
            flag: false,
            printerForm: {},
            viewModel: {
                isContain: '0',
            },
            editModel: {
                inspectionInformation: '0',
            },
            approvalModel: {
                auditResult: '0',
                auditNotifier: null,
                auditCause: '',
                initiatorDept: '',
                initiatorName: '',
            },
            selBtn: 1,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            stemList: [],
            // 总条数
            total: 0,
            // 字典表格数据
            incomingList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            selectRows: [],
            rowifInspect: '',
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 20,
                ruleCode: undefined,
                materialName: undefined,
                materialType:undefined,
                materialCode:undefined,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                ruleCode: [
                    { required: true, message: '规则编号不能为空', trigger: 'blur', },
                ],
                currentTactics:[
                    { required: true, message: '关联策略不能为空', trigger: 'blur', },
                ]
            },
            fullscreen: false,
            oldVersionVisiable: false,
            tableKey: 0,


            // 表格数据
            tableData: [],
            ruleOpen: false, // 新增&编辑转移规则弹窗
            ruleModal: {
                // id 主键
                id: undefined,
                // 规则编码
                ruleCode: undefined,
                // 物料
                materialCode: undefined,
                materialName: undefined,
                // 当前策略
                currentTactics: void 0,

            },
            codes: [], // ruleCode 集合
            tacticsOptions:[],  // 关联策略类型配置数组
            tacticsLoading: false,

            // file 文件列表
            rowId: '',
            itemFileList: [], // 文件列表
            otherList: [],
            trialBizTypeList:[],

        }
    },
    mounted() {
        console.log('mounted')
        this.getList()
        // this.getFactoryList()
        // this.getLocation()
    },
    activated() {
        console.log('activated')
        this.getList()
        // this.getLocation()
        // this.getFactoryList()
    },

    computed: {
        ...mapGetters(['userId', 'name', 'deptName']),
        ...mapState({
            isFold: (state) => state.app.isFold,
        }),
    },
    watch: {
        isFold(val) {
            if (val === true) {
                this.tableHeight = 'calc(100vh - 308px)'
            } else {
                this.tableHeight = 'calc(100vh - 466px)'
            }
        },
    },
    methods: {
        changeFlaw(item, scope, index) {
            this.ncrModel.voList[scope.$index].flawList[index].minFlawName =
                item.minFlawName
            this.ncrModel.voList[scope.$index].flawList[index].minFlawCode =
                item.minFlawCode
            this.ncrModel.voList[scope.$index].flawList[index].minFlawId =
                item.id
            console.log(item, '==============')
        },
        deleteFlaw(scope) {
            this.ncrModel.voList[scope.$index].flawList.splice(scope.$index, 1)
        },
        addFlaw(scope) {
            this.ncrModel.voList[scope.$index].flawList.push({
                minFlawNr: null,
                minFlawName: null,
                minFlawId: null,
                minFlawCode: null,
                classId: this.ids.join(','),
            })
        },
        getFactoryList() {
            listAllFactory().then((res) => {
                this.factoryList = res.data
            })
        },
        handleSave(row, index) {
            console.log('flag===', this.flag)
            if (this.flag) {
                return
            }
            this.flag = true
            editAcceptReturns(row)
                .then((res) => {
                    this.$nextTick(() => {
                        this.returnList[index] = res.data
                        this.returnKey++
                    })
                    this.flag = false
                    this.$modal.msgSuccess('操作成功!')
                })
                .catch((err) => {
                    this.returnList[index].storageFailure = err
                    this.flag = false
                })
        },
        returnChange(val, row, index) {
            this.returnList[index].acceptAmount = (
                parseFloat(row.batchAmount) - parseFloat(val)
            ).toFixed(0)
        },
        acceptChange(val, row, index) {
            this.returnList[index].returnAmount = (
                parseFloat(row.batchAmount) - parseFloat(val)
            ).toFixed(0)
        },
        handleReFixed(row) {
            getAcceptReturns({ id: row.id }).then((res) => {
                this.returnList = res.data

                this.returnInspection = true
            })
        },

        handleReleaseOpen() {
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.releaseOpen = true
        },
        submitRelease() {
            getReleaseApproval({
                id: this.ids[0],
                release: this.releaseForm.release,
            }).then((response) => {
                this.$modal.msgSuccess('操作成功!')
                this.releaseOpen = false
                this.getList()
            })
        },
        userDataCallback(userId) {
            this.approvalModel.auditNotifierId = userId
            this.$refs.approvalModel.validateField('auditNotifier')
        },
        formatAuditOpinion(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_AUDIT_RESULT.find((item) => {
                    return item.value === e
                })
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },
        incomingFileChange(e) {
            let ids = e.map((item) => item.id)
            console.log('-------', ids)
            if (ids.length) {
                this.approvalModel.fileId = ids.join(',')
            }
        },
        showSelect(e, materialType) {
            if (e) {
                this.optionLoading = true
                getMinFlawAll({}).then((res) => {
                    this.minFlawOptions = res.data
                    this.optionLoading = false
                })
            }
            console.log(e)
        },
        columnsCallback(incomingColumns) {
            console.log('incomingColumns', incomingColumns)
            localStorage.setItem(
                'incomingColumns',
                JSON.stringify(incomingColumns)
            )
            this.tableKey++
        },
        materialTypeRemoteMethod(val, cb) {
            listMaterialType({ typeName: val }).then((res) => {
                cb(res.rows)
            })
        },
        handleMaterialTypeSelect(e, scope) {
            // this.dialogForm.materialType = e
            this.queryParams.materialMin = e.typeName
            this.$forceUpdate()
        },
        formatExemptedOaStatus(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_EXEMPTEDOASTATUS.find(
                    (item) => {
                        return item.value === e
                    }
                )
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },
        // 获取小缺陷
        getMinFlaw() {
            // getMinFlawAll().then((res) => {
            //     this.minFlawOptions = res.data
            // })
        },
        formatOrderStatus(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_SHEET_STATUS.find((item) => {
                    return item.value === e
                })
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },
        formatUsingDecision(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_NCR_DECISION.find((item) => {
                    return item.value === e
                })
                console.log(e)
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },
        formatUsingDecisionTag(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_NCR_DECISION.find((item) => {
                    return item.value === e
                })
                if (obj) {
                    if (obj.label === '合格接受') {
                        return 'greenTag'
                    } else if (obj.label === '不接受') {
                        return 'redTag'
                    } else {
                        return 'yellowTag'
                    }
                }
            } else {
                return ''
            }
        },
        //
        formatTactics(e){
            if(e){
                let obj = this.dict.type.NYIQC_RULE_TACTICS.find((item) => item.value === e)
                return obj?.label
            }
            return ''
        },
        // 检验单状态变色
        sheetColorChange(row) {
            switch (row.sheetStatus) {
                case '0':

                case '1':
                case '2':
                    return 'labelColor1'
                case '3':
                    return 'labelColor0'
                case '4':
                case '5':
                    return 'labelY'
                default:
                    if (row.sheetStatus) {
                        return 'labelColor1'
                    }
            }
        },
        oaStatusColorChange(status) {
            switch (status) {
                case '0':
                    return 'labelY'
                case '1':
                    return 'labelColor0'
                case '2':
                    return 'labelColor1'
            }
        },
        getLocation() {
            // listALLStemLocation().then((response) => {
            //     this.stemList = response.data
            // })
        },
        submitNcrForm() {
            let files = []
            if (this.ncrModel.file1) {
                files.push(this.ncrModel.file1)
            }
            if (this.ncrModel.file2) {
                files.push(this.ncrModel.file2)
            }
            let submitData = {
                ...JSON.parse(JSON.stringify(this.ncrModel)),
                flawBizType: 'FLAW_UPLOAD',
                specificationBizType: 'SPECIFICATION_UPLOAD',
                fileId: files.join(','),
            }
            submitData.voList.forEach((io) => {
                io.flawChoice = io.flawChoice ? io.flawChoice.join(';') : ''
            })
            delete submitData.file1
            delete submitData.file2
            addNcr(submitData)
                .then((response) => {
                    this.$modal.msgSuccess('提交成功')
                    this.addInspection = false
                    this.getList()
                })
                .catch(() => {})
        },
        changeStem(e, scope, index) {
            this.ncrModel.voList[scope.$index].stemVoList[index].stemName = e
            this.ncrRefresh = this.ncrRefresh + 1
        },
        changeStemNumber(e, scope, index) {
            this.ncrModel.voList[scope.$index].stemVoList[index].stemNumber = e
            this.ncrRefresh = this.ncrRefresh + 1
        },
        addStem(scope) {
            let stemVoList = scope.row.stemVoList
            console.log(this.ncrModel.voList[scope.$index].stemVoList)
            this.ncrModel.voList[scope.$index].stemVoList.push({})
            this.ncrRefresh = this.ncrRefresh + 1
        },
        deleteStem(scope, index) {
            if (this.ncrModel.voList[scope.$index].stemVoList.length === 1) {
                this.$modal.msgWarning('请至少保留一条遏制信息!')
                return
            }
            this.ncrModel.voList[scope.$index].stemVoList.splice(index, 1)
            this.ncrRefresh = this.ncrRefresh + 1
        },
        factoryChange(e) {
            let obj = this.factoryList.find((item) => {
                return item.factoryName === e
            })
            this.ncrModel.launchFactory = obj.factoryName
        },
        getFactoryList() {
            listALLFactory().then((res) => {
                this.factoryList = res.data
            })
        },
        drawerClose() {
            this.drawer = false
        },
        getNowDate() {
            var date = new Date()
            var y = date.getFullYear()
            var m = date.getMonth() + 1
            var d = date.getDate()
            //  当前日期
            return (
                y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d)
            )
        },
        /** 查询字典类型列表 */
        getList() {
            this.loading = true
            let params = { ...this.queryParams }
            getMaterialBindList(this.queryParams).then(res=>{

                    this.tableData = res?.rows??[]
                    this.total = res?.total??0
                    this.loading = false
                    this.tableHeight = this.isFold
                        ? 'calc(100vh - 308px)'
                        : 'calc(100vh - 466px)'

            }).finally(()=>{
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                dictId: undefined,
                dictName: undefined,
                dictType: undefined,
                status: '0',
                remark: undefined,
            }

            this.resetForm('form')
            this.queryParams.sheetStatus = ['9']
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = []
            this.queryParams.exceedTimeStauts = null
            this.queryParams.id = null
            this.queryParams={
                pageNum: 1,
                pageSize: 20,

                ruleCode: undefined,
                materialName: undefined,
                materialType:undefined,
                materialCode:undefined,
            }
            this.resetForm('queryForm')
            this.handleQuery()
        },
        handleAddIncoming() {
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            getInspectionCheck({ id: this.ids[0] }).then((response) => {
                this.$router.push({
                    path: '/addIncoming/index/' + this.ids[0],
                    query: { ifInspect: this.rowifInspect },
                })
            })
        },
        handleNcr() {
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            let selectRows = [...this.selectRows]
            selectRows.forEach((io) => {
                io.inspectionId = io.id
                io.stemVoList = [{}]
            })
            console.log(this.selectRows)
            getNcrReviewCheck({ ids: this.ids.join(',') }).then((response) => {
                if (response.code === 200) {
                    getNCRDetail({ ids: this.ids.join(',') }).then(
                        (ncrData) => {
                            if (ncrData.code === 200) {
                                let voList = ncrData.data.voList
                                voList.forEach((element) => {
                                    element.stemVoList = [{}]
                                    element.flawChoice = element.flawChoice
                                        ? element.flawChoice.split(';')
                                        : element.flawChoice
                                    element.flawList = [
                                        {
                                            minFlawNr: null,
                                            minFlawName: null,
                                            minFlawId: null,
                                            minFlawCode: null,
                                            classId: this.ids.join(','),
                                        },
                                    ]
                                })
                                this.ncrModel = {
                                    voList: voList,
                                    whetherStem: '2',
                                    ncrType: ncrData.data.ncrType,
                                }

                                this.addInspection = true
                            }
                        }
                    )
                    this.getMinFlaw()
                }
            })
        },
        handlePrinter() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            getPrintCheck({ ids: this.ids.join(',') }).then((response) => {
                if (response.code === 200) {
                    this.printerOpen = true
                }
            })
        },

        handleReturn() {
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            getReturn({ id: this.ids[0] }).then((response) => {
                this.$modal.msgSuccess('退回成功!')
                this.getList()
            })
        },
        handleSelectUse(row) {
            this.$router.push({
                path: '/incomingDetail/selectUse/0',
                query: {
                    id: row.id,
                    materialCode: row.materialCode,
                    materialName: row.materialName,
                    supplierCode: row.supplierCode,
                    inspectionLotMark: row.inspectionLotMark,
                    lot: row.lot,
                    ncrProcessId: row.ncrProcessId,
                },
            })
        },
        handleAddtionRecording() {
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            getCollectionCheck({ id: this.ids[0] }).then((response) => {
                this.$router.push({
                    path: '/additionData/index/' + this.ids[0],
                })
            })
        },
        handlePass() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            getReleaseCheck({ ids: this.ids.join(',') }).then((response) => {
                this.$router.push({ path: '/pass/index/' + this.ids.join(',') })
            })
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.ruleOpen = true
        },
        handleReview() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.$modal
                .confirm(this.$t('formValidation.confirm'))
                .then(() => {
                    getReview({ ids: this.ids.join(',') }).then((response) => {
                        this.$modal.msgSuccess('操作成功!')
                        this.getList()
                    })
                })
                .catch(() => {})
        },
        handleApproval() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            getAuditCheck({ id: this.ids[0] }).then((response) => {
                getAuditEcho({ id: this.ids[0] }).then((response) => {
                    this.approvalModel = response.data
                    let auditCause = []
                    response.data.flawList.forEach((io) => {
                        auditCause.push(io.minFlawName)
                    })
                    this.auditCause = auditCause.join(';')
                })

                this.approvalOpen = true
            })
        },
        tableRowClassName({ row, rowIndex }) {
           
            if (row.isHighLight === true) {
                console.log('rowIndex', row)
                return 'rowHighLight' //若isHighLight为true，则使用“rowHighLight”样式
            } else {
                return ''
            }
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            console.log(selection)
            // if (selection.length === 0) {
            //     return
            // }
            this.selectRows = selection
            if (selection.length > 0) {
                this.rowifInspect = selection[0].ifInspect
            }
            this.ids = selection.map((item) => item.id)
            this.codes = selection.map((item) => item.ruleCode)
            console.log('this.ids', this.ids)
            this.incomingList.forEach((io, index) => {
                console.log('includes', this.ids.includes(io.id))
                if (this.ids.includes(io.id)) {
                    io.isHighLight = true
                } else {
                    io.isHighLight = false
                }
            })
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const dictId = row.dictId || this.ids
            getType(dictId).then((response) => {
                this.form = response.data
                this.open = true
                this.title = '修改字典类型'
            })
        },
        /** 提交按钮 */
        submitForm: function () {
            this.open = false
        },
        submitApproval: function () {
            this.approvalOpen = false
            let submitData = {
                ...this.approvalModel,
                realityAuditName: this.name,
                realityAuditId: this.userId,
                id: this.ids[0],
            }
            if (this.approvalModel.auditResult === '0') {
                delete submitData.auditResult
            }

            getAudit(submitData).then((response) => {
                this.$modal.msgSuccess('审核成功')
                this.getList()
            })
        },
        // 提交转移规则
        submitRule(){
            let validRes = false;
            this.$refs['ruleFormRef'].validate((valid) => {
                validRes = valid
            })
            if(!validRes) return this.$modal.msgWarning(this.$t('formValidation.pleaseCompleteTheForm'))

            const {materialCode,currentTactics} = this.ruleModal
            let submitData = {materialCode,currentTactics,id:this.rowId}
            editMaterialTactics(submitData).then(res=>{
                if(res?.code == 200){
                    this.$modal.msgSuccess('物料策略保存成功')
                    this.getList()
                    this.ruleOpen = false;
                }
            })
        },
        /** 发起检验提交 */
        submitAddForm: function () {
            this.$modal.msgSuccess('发起成功!')
            this.addInspection = false
        },
        submitPrinter: function () {
            this.$modal.msgSuccess('打印成功!')
            this.printerOpen = false
        },

        /** 查看按钮操作 */
        handleView(scope) {
            this.$router.push({ path: '/incomingDetail/index/' + scope.row.id })
        },
        /** 打印预览操作 */
        handlePrinterView(scope) {
            getReport({ id: scope.row.id }).then((res) => {
                let reportId = res.data ? res.data : '791117854038990848'
                let a = document.createElement('a')
                a.href =
                    process.env.VUE_APP_BASE_API +
                    '/jimu/jmreport/view/' +
                    reportId +
                    '?token=' +
                    getToken() +
                    '&id=' +
                    scope.row.id
                a.target = '_blank'
                a.style.display = 'none'
                document.body.appendChild(a)
                a.click()
                a.remove()
                // this.$router.push({
                //     path: '/incoming/printerPreview/' + scope.row.id,
                //     query: {
                //         usingDecision: scope.row.usingDecision,
                //     },
                // })
            })
        },
        /** 编辑按钮操作 */
        handleEdit(row) {
            Object.assign(this.ruleModal,row.id ?row:this.$options.data().ruleModal)
            this.ruleOpen = true
            this.remoteFatch(row)
            this.rowId = row?.id ?? ''
            row?.id && this.geFileByBiz(row.id)
        },
        /** 关闭抽屉操作 */
        handleClose(row) {
            this.drawer = false
        },
        /** 导出按钮操作 */
        handleExport() {
            let params = { ...this.queryParams }
            params.sheetStatus = params.sheetStatus.join(',')
            // params.maturity = params.maturity.join(',')
            if (params.inspectionTime && params.inspectionTime.length) {
                params.params.beginTime = params.inspectionTime[0]
                params.params.endTime = params.inspectionTime[1]
            } else {
                params.params.beginTime = ''
                params.params.endTime = ''
            }
            delete params.inspectionTime
            if (params.checkoutEndTime && params.checkoutEndTime.length) {
                params.params.endBeginTime = params.checkoutEndTime[0]
                params.params.endEndTime = params.checkoutEndTime[1]
            } else {
                params.params.endBeginTime = ''
                params.params.endEndTime = ''
            }
            delete params.checkoutEndTime
            this.download(
                'ny-iqc/incomingInspection/export',
                {
                    ...params,
                },
                `type_${new Date().getTime()}.xlsx`
            )
        },
        handleExportTemplate() {
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.download(
                'ny-iqc/incomingInspection/exportById?id=' + this.ids[0],
                {},
                `type_${new Date().getTime()}.xlsx`
            )
        },
        handleExportDetail() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.download(
                'ny-iqc/incomingInspection/exportDetails?ids=' +
                    this.ids.join(','),
                {},
                `type_${new Date().getTime()}.xlsx`
            )
        },
        /** 刷新缓存按钮操作 */
        handleRefreshCache() {
            refreshCache().then(() => {
                this.$modal.msgSuccess('刷新成功')
            })
        },
        imgFileChange1(e) {
            let ids = e.map((item) => item.id)
            console.log('-------', ids)
            if (ids.length) {
                this.ncrModel.file1 = ids.join(',')
            }
        },
        imgFileChange2(e) {
            let ids = e.map((item) => item.id)
            if (ids.length) {
                this.ncrModel.file2 = ids.join(',')
            }
        },
        // 点击删除
        handleDel(scope){
            this.$modal
                .confirm('是否确认删除选中的免检单？')
                .then(() => {
                    delTransferRules(scope.row.id).then((response) => {
                        this.$modal.msgSuccess(this.$t('tips.deleteSuccess'))
                        this.getList()
                    })
                })
                .catch(() => {})

            return
            if (this.ids.length === 0) {
                this.$modal.msgWarning('请至少选择一条免检单!')
                return
            }
            this.$modal
                .confirm('是否确认删除选中的免检单？')
                .then(() => {
                    delTransferRules(this.ids.join(',')).then((response) => {
                        this.$modal.msgSuccess(this.$t('tips.deleteSuccess'))
                        this.getList()
                    })
                })
                .catch(() => {})
        },
        // 状态过滤
        statusfilter(row) {
            if (row.status) {
                let obj = this.dict.type.NYIQC_ENABLE_STATUS.find((item) => (item.value === row.status))
                return obj?.label??''
            } else {
                return ''
            }
        },
        // 事业部弹窗回调
        divisionCB(record){
            this.ruleModal.divisionId = record.divisionId
        },
        // 点击编辑物料接口
        handleMaterial({row}){
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.$router.push({
                    name: 'editMaterial',
                    query: { ruleId:this.ids[0],ruleCode: this.codes[0], },
                })
        },

        // 跳转策略类型维护
        handlePolicyType(){
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.$router.push({
                    path: '/transferRules/editPolicyType',
                    query: { ruleId:this.ids[0],ruleCode: this.codes[0], },
                })
        },
        // 跳转策略类型维护
        toeditPolicyType(){
            console.log(this.ids)
            if(this.ids.length==1){
                var obj=this.tableData.filter(item=>item.id==this.ids[0])[0]
                console.log(obj)
                this.$router.push({
                    path: '/transferRules/editPolicyType',
                    query: {
                        ruleCode: obj.ruleCode,
                        ruleName: obj.ruleName,
                        divisionName: obj.divisionName,
                    }
                })
            }

        },
        // 点击策略类型
        handlePolicyType(){
            if (this.ids.length !== 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }

            this.$router.push({
                name: 'editPolicyType',
                query: { ruleId:this.ids[0],ruleCode: this.codes[0], },
            })
        },
        updateStatus(status, row) { // 1 开启， 2 关闭
            let data = { ...row }

            console.log(status,row)
            data.status = status
            editTransferRules(data).then(res=>{
                console.log(res)
                if(res.code == 200)return this.$modal.msgSuccess(`${status == '1'?'开启':'关闭'}成功！`)
                this.$modal.msgWarning(`${status == '1'?'开启':'关闭'}失败！`);
                this.getList()
            })
        },
        // 点击删除事件
        handleDelete(){
            if (this.ids.length < 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }

            this.$modal
                .confirm(this.$t('formValidation.delRuleConfirm'))
                .then(() => {
                    console.log(this.ids)
                    let ids = this.ids.join(',')
                    delTransferRules(ids).then((res) => {
                        if(res.code == 200) {
                            this.$modal.msgSuccess(this.$t('tips.deleteSuccess'))
                            this.getList()
                        }
                    })
                })
                .catch(() => {})
        },
        handleStrategy(){
            if (this.ids.length < 1) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.$router.push({
                    path: '/transferRules/editStrategy',
                    query: { ruleId:this.ids[0],ruleCode: this.codes[0], },
                })
        },
        // 当前策略远程搜索方法
        remoteFatch(record) {
            this.tacticsLoading = true;
            carryOutList({ruleCode:record?.ruleCode}).then((res) => {
                if(Array.isArray(res.rows) ) {res
                    var typelist = this.dict.type.NYIQC_RULE_TACTICS
                    // typelist.filter(item=>item.value)
                    var list = res.rows
                    this.tacticsOptions = []
                    for (let i = 0; i < typelist.length; i++) {
                         for (let index = 0; index < list.length; index++) {
                             if(list[index].currentTactics==typelist[i].value){
                                this.tacticsOptions.push(typelist[i])
                                break
                             }
                         }
                    }
                }else {
                    this.tacticsOptions = [];
                }
            }).finally(()=>{
                this.tacticsLoading = false
            })
        },
        // 获取文件列表
        geFileByBiz(id) {
            geFileByBiz({ bizId: id }).then((res) => {
                let otherList = []
                let trialBizTypeList=[]
                res.data.forEach((io) => {
                    if (io.bizType === 'UPLOAD_FILE_OTHERS') {
                        otherList.push(io)
                    }
                    if (io.bizType === 'trialBizType') {
                        trialBizTypeList.push(io)
                    }
                })
                this.otherList = otherList
                this.trialBizTypeList=trialBizTypeList
                this.$forceUpdate()
            })
        },
        // 文件上传事件
        itemFileChange(fileList){

        }
    },
}
</script>
<style lang="scss" scoped>
::v-deep .el-card {
    padding-top: 20px;
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    padding-bottom: 20px;
}
::v-deep .el-aside {
    padding: 0;
    margin-bottom: 0;
}
.content-style {
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 2px;
    background-color: white;
    margin-top: 10px;
}
::v-deep .el-button-group .selBtn {
    background: #fff;
    border: 1px solid #0b7be3;
    color: #0b7be3;
}
::v-deep .el-button-group .unselBtn {
    background: #fff;
    border: 1px solid #ededf2;
    color: #666666;
}
.header-left {
    float: left;
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    line-height: 40px;
    display: flex;
    justify-content: center;
    border-bottom: 2px solid #0b7be3;
}
.header-right {
    float: right;
}
.container-header {
    float: left;
    width: 100%;
    border-bottom: 1px solid #ededf2;
}
.container-table {
    float: left;
    margin-top: 6px;
    width: 100%;
}
.mb8 {
    float: left;
    margin-top: 6px;
    width: 100%;
}
::v-deep .el-form-item {
    margin-bottom: 5px;
}
.drawer-footer {
    display: flex;
    position: relative;
    z-index: 9999;
    bottom: -40px;
    height: 40px;
    justify-content: center;
    width: 100%;
}
.drawer-close {
    background: #f7f8fa;
    border-color: #f7f8fa;
}
::v-deep .form-input .el-form-item__content {
    width: 185px;
}
::v-deep .el-dialog--center .el-dialog__body {
    padding: 15px 30px;
}
.smallRadio {
    ::v-deep .el-radio__label {
        font-size: 12px;
    }
}
.greenTag {
    position: relative;
    left: 5px;
    padding-left: 10px;
}
.redTag {
    position: relative;
    left: 5px;
    padding-left: 10px;
}
.yellowTag {
    position: relative;
    left: 5px;
    padding-left: 10px;
}
::v-deep .table-fixed {
    .el-table__fixed-right {
        height: 98.5% !important;
        background: #fff;
    }
    .el-table__fixed {
        height: 98.5% !important;
        background: #fff;
    }
}
::v-deep .rowHighLight {
    background: oldlace;
}
::v-deep .el-dialog__body {
    max-height: 500px;
    overflow-y: auto;
}
::v-deep ::-webkit-scrollbar {
      width: 10px !important;
      height:10px !important;

}
::v-deep .el-table__fixed::before, .el-table__fixed-right::before {
    content: '';
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 1px;
    background-color: unset;
    z-index: 4;
}
</style>
